package com.star.gateway.filter;

import com.star.common.core.utils.ServletUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.regex.Pattern;

/**
 * 黑名单过滤器
 *
 * @author zhouhengzhe
 */
@Component
public class BlackListUrlFilter extends AbstractGatewayFilterFactory<BlackListUrlFilter.Config> {
    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {

            String url = exchange.getRequest().getURI().getPath();
            if (config.matchBlacklist(url)) {
                return ServletUtils.webFluxResponseWriter(exchange.getResponse(), "请求地址不允许访问");
            }

            return chain.filter(exchange);
        };
    }

    public BlackListUrlFilter() {
        super(Config.class);
    }

    public static class Config {
        private List<String> blackListUrl;

        private final List<Pattern> blackListUrlPattern = Lists.newArrayList();

        public boolean matchBlacklist(String url) {
            return !blackListUrlPattern.isEmpty() && blackListUrlPattern.stream().anyMatch(p -> p.matcher(url).find());
        }

        public List<String> getBlackListUrl() {
            return blackListUrl;
        }

        public void setBlackListUrl(List<String> blackListUrl) {
            this.blackListUrl = blackListUrl;
            this.blackListUrlPattern.clear();
            this.blackListUrl.forEach(url ->
                    this.blackListUrlPattern.add(Pattern.compile(url.replaceAll("\\*\\*", "(.*?)"), Pattern.CASE_INSENSITIVE))
            );
        }
    }

}
